<?php

declare(strict_types=1);

namespace app\common\model;

use app\common\facade\Target;

// use app\common\tool\pay\Pay;
//use app\common\tool\Target\Driver\Account;
use think\facade\Cache;
use think\facade\Event;
use app\common\facade\Pay;
use app\common\controller\Config;

class Order extends Base
{
    protected $name = 'order';

    public function commission1()
    {
        return $this->hasOne(User::class, 'id', 'commission_uid1')->field('id,code,nickname');
    }

    public function commission2()
    {
        return $this->hasOne(User::class, 'id', 'commission_uid2')->field('id,code,nickname');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile,photo');
    }

    public function address()
    {
        return $this->hasOne(Address::class, 'id', 'address_id');
    }

    public function express()
    {
        return $this->hasOne(Express::class, 'id', 'express_id');
    }

    public function p()
    {
        return $this->hasOne(Area::class, 'code', 'province')->field('code,province as title');
    }

    public function c()
    {
        return $this->hasOne(Area::class, 'code', 'city')->field('code,city as title');
    }

    public function d()
    {
        return $this->hasOne(Area::class, 'code', 'district')->field('code,district as title');
    }

    public function t()
    {
        return $this->hasOne(Area::class, 'code', 'town')->field('code,town as title');
    }

    public function products()
    {
        return $this->hasMany(OrderProduct::class, 'order_id');
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    public function getStatusAttr($value)
    {
        return getOrderStatus($value);
    }

    public function getPostTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '未发货';
    }

    public static function getTakeOverTableList($that, $param, $filed = '*', $count = 0)
    {
        try {
            foreach ($that as &$v) {
                $products = $v->products()->field('pid,product_title,num,product_image,spec,shoptype')->select()->toArray();
                foreach ($products as $k => $item) {
                    $icon = $item['product_image'];
                    if (!empty($item['spec'])) {
                        $spce = explode('-', $item['spec']);
                        if ($item['shoptype'] == 'lntegral') {
                            $Specname = LntegralSpecItem::whereIn('id', $spce)->column('name');
                        } else {
                            $Specname = SpecItem::whereIn('id', $spce)->column('name');
                        }
                        if (!empty($Specname)) {
                            $guige = '规格：' . implode('-', $Specname);
                        } else {
                            $guige = '规格：默认';
                        }
                    } else {
                        $guige = '规格：默认';
                    }
                    $html = '<a href="javascript:;" class="openShowImg" data-value="' . $icon . '"><img src="' . $icon . '" style="width: 20px; height:20px;border-radius: 5px;margin-right: 5px"/></a>';
                    $v->product .= '<p>' . $html . $item['product_title'] . '《' . $guige . '》' . '《数量：' . $item['num'] . "》</p>";
                }
                $v->pay_time = $v->pay_time ? date('Y-m-d H:i:s', intval($v->pay_time)) : '待付款';
                $v->statusRaw = $v->getData('status');
            }
            return ['code' => 0, 'data' => $that, 'count' => $count];
        } catch (\Exception $e) {
            return [];
        }
    }


    /**
     * @param $param -- 提交的参数
     * @param $admin -- 后台当前登录管理员
     * @return array
     * 原点 2022年1月8日16:45:49 后台发货订单
     */
    public static function deliver($param, $admin)
    {

        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }
            $status = $info->status;


            $info->receiver = $param['receiver'];
            $info->receiver_tel = $param['receiver_tel'];
            $info->province = $param['province'];
            $info->city = $param['city'];
            $info->district = $param['district'];
            // $info->town = $param['town'];
            $info->address_details = $param['address_details'];
            $m = '已修改';
            if ($info->getData('status') > 1) {
                $info->express_id = $param['express_id'];
                $info->express_code = $param['express_code'];
                $info->post_remark = $param['post_remark'];
                $info->post_time = time();
                $info->status = 3;
                $res = $info->save();
                if ($res !== true) {
                    return ['code' => -1, 'msg' => '发货失败'];
                }
                if ($status < 3) {
                    $msg = '订单发货，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                    $m = '已发货';
                } else {
                    $msg = '修改了发货信息，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                }
            } else {
                $res = $info->save();
                if ($res !== true) {
                    return ['code' => -1, 'msg' => '修改失败'];
                }
                $msg = '修改订单地址，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
            }


            Logs::adds($msg, $admin->id, $admin->admin_name);
            return ['code' => 1, 'msg' => $m];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 修改运费
     */
    public static function savePostage($param, $admin)
    {

        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }
            if ($param['postage'] < 0 || $param['postage'] == '') {
                return ['code' => -1, 'msg' => '运费不能小于0元'];
            }
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '订单状态异常！'];
            } else {
                $info->real_amount = $info->real_amount - $info->postage + $param['postage'];
                $info->total_amount = $info->total_amount - $info->postage + $param['postage'];
                $info->postage = $param['postage'];
                $res = $info->save();
                if ($res !== true) {
                    return ['code' => -1, 'msg' => '修改运费失败'];
                }
                $msg = '修改订单运费，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
            }
            Logs::adds($msg, $admin->id, $admin->admin_name);
            return ['code' => 1, 'msg' => '修改运费成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 修改实付金额
     */
    public static function saveMoney($param, $admin)
    {

        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }
            if ($param['real_amount'] < 0 || $param['real_amount'] == '') {
                return ['code' => -1, 'msg' => '实付金额不能小于0元'];
            }
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '订单状态异常！'];
            } else {
                $info->real_amount = $param['real_amount'];
                $res = $info->save();
                if ($res !== true) {
                    return ['code' => -1, 'msg' => '修改实付金额失败'];
                }
                $msg = '修改订单实付金额，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
            }
            Logs::adds($msg, $admin->id, $admin->admin_name);
            return ['code' => 1, 'msg' => '修改实付金额成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param $uid -- 会员ID
     * @return array
     * 原点 2022年1月8日16:45:24 获得会员临时暂存的订单
     */
    public static function getTemporary($user): array
    {
        try {
            $uid = $user->id;
            $syytem = Config::lists();
            $temporary = Cache::get('tsOrder_' . $uid);
            if (empty($temporary)) {
                return ['code' => -1, 'msg' => '加载失败'];
            }
            $infos = json_decode($temporary, true);
            $total = 0;
            $num = 0;
            $cate_1 = '';
            $commission1 = 0;
            $commission2 = 0;
            $products = [];
            $fullmoney = 0;
            $orderlist = [];
            $orderlists = [];
            $vip_money = 0;
            $m_count = 0; //秒杀商品个数
            foreach ($infos as $value) {
                $product = Product::where(['is_del' => 0, 'status' => 1, 'id' => $value['pid']])
                    ->field('id,title,icon,rule_by,rule_num,stock,ratio1,ratio2')->find();
                if (empty($product) || $product->stock <= 0) continue;
                $total += $value['price'] * $value['num'];
                $vip_money += ($value['shoptype'] == 'shop' ? User::loginPrice($uid, $value['price'] * $value['num']) : 0);
                $num += $value['num'];
                $product->num = $value['num'];
                $product->price = $value['price'];
                $c_price = $value['shoptype'] == 'shop' ? User::loginPrice($uid, $value['price']) : $value['price'];
                $commission1 += round(($c_price * $value['num'] * $syytem['tp_1']), 2);
                $commission2 += round(($c_price * $value['num'] * $syytem['tp_2']), 2);

                if ($value['shoptype'] != 'shop') {
                    $m_count++;
                }
                $ProductFull = ProductFull::getFull($product->id, $value['price'] * $value['num']); //满减
                if ($ProductFull['code'] != -1) {
                    $moneyyh = $ProductFull['list']['moneyyh'];
                } else {
                    $moneyyh = 0;
                }
                $fullmoney += $moneyyh; //满减金额
                $product->spec = $value['spec'];
                $product->ProductFull = $ProductFull;
                $product->seckill_id = $value['seckill_id'];
                $orderlist['id'] = $value['pid'];
                $orderlist['seckill_id'] = $value['seckill_id'];
                $orderlist['price'] = $value['price'];
                $orderlist['num'] = $value['num'];
                if (!$cate_1) $cate_1 = $value['cate_1'];
                $ids[] = $value['pid'];
                $products[] = $product;
                $orderlists[] = $orderlist;
            }
            if (count($infos) > 1) {
                $ProductFulls = ProductFull::getFullCart($infos, $ids); //满减购物车
                if ($ProductFulls['code'] != -1) {
                    $fullmoney = $ProductFulls['list']['moneyyh'];
                } else {
                    $fullmoney = 0;
                }
            }
            if ($user->level_id > 1) {
                $fullmoney = 0;
            }
            // if (!empty($ids)) {
            //     $full = implode(',', $ids);
            //     $manlist = ProductFull::whereIn('id', explode(',', $full))->where(['is_del' => 0])->order('money asc')->select();
            //     foreach ($manlist as $k => $v) {
            //         if ($total >= $v['money']) {
            //             $money[] = $v['id'];
            //         } else {
            //             $money[] = 0;
            //         }
            //     }
            // } else {
            //     $money[] = 0;
            // }
            // $fullid = max($money);
            // if ($fullid != 0) {
            //     $mfull = ProductFull::where(['id' => $fullid, 'is_del' => 0])->find();
            //     $fullmoney = $mfull['sale_money'];
            //     $fulltitle = $mfull['title'];
            // } else {
            //     $fullmoney = 0;
            //     $fulltitle = '';
            // }
            return [
                'products'    => $products,
                'total'       => sprintf('%.2f', $total),
                'cate_1'      => $cate_1,
                'num'         => $num,
                'fullmoney'   => $fullmoney > 0 ? $fullmoney : '',
                'infos'   => count($infos),
                'shoptype'    => $m_count == 0 ? 'shop' : 'seckill',
                'orderlist' => $orderlists,
                'commission1' => $commission1,
                'commission2' => $commission2,
                'address'     => Address::getDefault($uid, $total, $products, $num),
                'vip_money' => $vip_money
            ];
        } catch (\Exception $e) {
            return [];
        }
    }
    public static function getOrderTemporary($uid): array
    {
        try {
            $syytem = Config::lists();
            $temporary = Cache::get('tsOrder_' . $uid);
            if (empty($temporary)) {
                return ['code' => -1, 'msg' => '加载失败'];
            }
            $infos = json_decode($temporary, true);
            $total = 0;
            $num = 0;
            $cate_1 = '';
            $commission1 = 0;
            $commission2 = 0;
            $products = [];
            $vip_money = 0;
            $m_count = 0; //秒杀商品个数
            foreach ($infos as $value) {
                $product = Product::where(['is_del' => 0, 'status' => 1, 'id' => $value['pid']])
                    ->field('id,title,icon,stock,ratio1,ratio2')->find();
                if (empty($product) || $product->stock <= 0) continue;
                $total += $value['price'] * $value['num'];
                $vip_money += $value['shoptype'] == 'shop' ? User::loginPrice($uid, $value['price'] * $value['num']) : 0;
                $c_price = $value['shoptype'] == 'shop' ? User::loginPrice($uid, $value['price']) : $value['price'];
                $num += $value['num'];
                $product->num = $value['num'];
                $product->price = $value['price'];
                $commission1 += round(($c_price * $value['num'] * $syytem['tp_1']), 2);
                $commission2 += round(($c_price * $value['num'] * $syytem['tp_2']), 2);

                if ($value['shoptype'] != 'shop') {
                    $m_count++;
                }

                $product->shoptype = $value['shoptype'];

                $product->seckill_id = $value['seckill_id'];
                $product->spec = $value['spec'];
                if (!$cate_1) $cate_1 = $value['cate_1'];
                $products[] = $product;
            }
            return [
                'products'    => $products,
                'total'       => sprintf('%.2f', $total),
                'cate_1'      => $cate_1,
                'num'         => $num,
                'shoptype'    => $m_count == 0 ? 'shop' : 'seckill',
                'commission1' => $commission1,
                'commission2' => $commission2,
                'vip_money' => $vip_money
            ];
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * @param $address_id -- 选择地址ID
     * @param $user -- 会员信息
     * @return array
     * 原点 2022年1月8日16:44:54 提交产生待支付订单
     */
    public static function submit($param, $user): array
    {
        if (!$param['address_id']) {
            return ['code' => -1, 'msg' => '请选择收货地址'];
        }
        $address = Address::where('id', $param['address_id'])->find();
        if (empty($address)) {
            return ['code' => -1, 'msg' => '收货地址错误，请重新选择'];
        }
        $temporary = self::getOrderTemporary($user->id);

        if (empty($temporary) || empty($temporary['products'])) {
            return ['code' => -1, 'msg' => '加载失败，请稍后再试'];
        }
        if (!$temporary['total'] || $temporary['total'] <= 0) {
            return ['code' => -1, 'msg' => '订单价格错误！'];
        }
        parent::startTrans();
        try {
            //分销订单写入
            if ($param['user_id'] != 0) {
                $user1 = User::where(['id' => $param['user_id'], 'is_del' => 0, 'is_place' => 1])->find();
                if (!empty($user1) && $param['user_id'] != $user['id']) {
                    $commission_uid1 = $user1->id;
                    $commission1 = $temporary['commission1'];
                    if ($user1['parent_id'] != 0 && $user1['parent_id'] != 1) {
                        $user2 = User::where(['id' => $user1['parent_id'], 'is_del' => 0, 'is_place' => 1])->find();
                        if (!empty($user2)) {
                            $commission2 = $temporary['commission2'];
                            $commission_uid2 = $user2->id;
                        } else {
                            $commission2 = 0;
                            $commission_uid2 = 0;
                        }
                    } else {
                        $commission2 = 0;
                        $commission_uid2 = 0;
                    }
                } else {
                    $commission_uid1 = 0;
                    $commission1 = 0;
                    $commission2 = 0;
                    $commission_uid2 = 0;
                }
            } else {
                $commission_uid1 = 0;
                $commission1 = 0;
                $commission2 = 0;
                $commission_uid2 = 0;
            }

            $new = parent::create([
                'sn'              => date('Ymd') . $user->id . time(),
                'uid'             => $user->id,
                'address_id'      => $param['address_id'],
                'total_amount'    => $param['total_amount'],
                'real_amount'     => $param['real_amount'],
                'coupon_money'    => $param['coupon_money'],
                'fullmoney'       => $param['fullmoney'],
                'coupon_id'       => $param['coupon_id'],
                'make'            => $param['make'],
                'make_type'       => $param['make_type'],
                'make_status'     => $param['make_status'],
                'note'            => $param['note'],
                'types'           => $param['types'],
                'postage'         => $param['postage'],
                'order_type'      => $temporary['cate_1'],
                'shoptype'        => $temporary['shoptype'],
                'vip_money'        => $temporary['vip_money'],
                'commission1'     => $commission1,
                'commission_uid1' => $commission_uid1,
                'commission2'     => $commission2,
                'commission_uid2' => $commission_uid2,
                'receiver'        => $address->nickname,
                'receiver_tel'    => $address->tel,
                'province'        => $address->province,
                'city'            => $address->city,
                'district'        => $address->district,
                'address_details' => $address->details,
            ]);
            $flag = OrderProduct::add($temporary['products'], $new->id, $user->id);
            if ($flag['code'] != 1) {
                parent::rollback();
                return ['code' => -1, 'msg' => $flag['msg']];
            }
            if ($param['coupon_id'] != 0) {
                Usercoupon::where(['id' => $param['coupon_id']])->update(['status' => 1]);
            }

            parent::commit();
            Cart::clearCart($user->id);
            Cache::set('nowOrderId_' . $user->id, $new->id);
            return ['code' => 1, 'msg' => '已生成订单'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid -- 会员ID
     * @return array
     * 原点 2022年1月8日16:44:08 获取当前会员待支付的订单
     * 每个会员同时只能下一个单，如有多个会替换掉！
     */
    public static function getNowOrder($uid): array
    {
        $now_id = Cache::get('nowOrderId_' . $uid);
        if (!$now_id) {
            return ['code' => -1, 'msg' => '加载失败'];
        }
        $info = parent::where(['id' => $now_id, 'uid' => $uid, 'status' => 1, 'pay_state' => 0])->find();
        if (empty($info)) {
            return ['code' => -1, 'msg' => '订单不存在或已支付'];
        }
        return ['code' => 1, 'result' => $info];
    }

    /**
     * @param $param -- 支付提交参数
     * @param $user -- 会员信息
     * @return array
     * 原点 2022年1月8日16:42:30 确认支付
     */
    public static function confirmPayment($param, $user): array
    {
        $info = self::getNowOrder($user->id);
        if ($info['code'] != 1) return $info;
        $order = $info['result'];

        $account = $param['pay_way'];
        // print('<pre>');print_r($param);die;
        $return_url = 'http://' . $_SERVER['HTTP_HOST'] . '/index/order/my_order?state=2';
        if ($param['types'] == 1) {

            switch ($account) {
                case "currency":
                case "bonus":
                    if ($user->assets->$account < $order->real_amount) {
                        return ['code' => -1, 'msg' => '账户余额不足'];
                    }
                    return self::operation($order, $user, $account, $param);
                case "wechat":
                    $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/api/callback/weChatOrder';
                    $options = Pay::setDriver('WeChat')
                        ->basic('购买商品', $order->sn, $order->real_amount, $notifyUrl)
                        ->setOpenId($user->openid)
                        ->create('JSAPI');
                    return ['code' => 1, 'data' => $options];
                case "alipay":
                    $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/index/callback/aliPayOrder';

                    $options = Pay::setDriver('AliPay')
                        ->setReturnUrl('同步跳转地址')
                        ->basic('购买商品', '订单号', '支付金额', '回调地址')
                        ->create('Web');
                    return ['code' => 1, 'data' => $options];
                default:
                    return ['code' => -1, 'msg' => '请选择支付方式'];
            }
        } else {
            if ($account == '') {
                return ['code' => -1, 'msg' => '请选择支付方式'];
            }
            if ($param['images'] == '') {
                return ['code' => -1, 'msg' => '请上传打款截图'];
            }
            return self::operation($order, $user, $account, $param);
        }
    }


    /**
     * @param $param -- 支付提交参数
     * @param $user -- 会员信息
     * @return array
     * 原点 2022年1月8日16:42:30 确认支付
     */
    public static function payAgent($param, $user): array
    {
        $order = parent::where(['id' => $param['id'], 'is_del' => 0])->with(['products'])->find();
        if (empty($order)) {
            return ['code' => -1, 'msg' => '订单不存在'];
        }
        if ($order['status'] != '待付款') {
            return ['code' => -1, 'msg' => '该订单异常'];
        }
        if (isset($param['lx']) && $param['lx'] == 1) { //类型1代付  否则是重新付款
            if ($order['uid'] == $user->id) {
                return ['code' => -1, 'msg' => '自己的订单不可代付'];
            }
        }
        $account = $param['pay_way'];
        if ($param['types'] == 1) {
            switch ($account) {
                case "payment":
                    $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/api/callback/weChatOrder';
                    $options = Pay::setDriver('WeChat')
                        ->basic($order->products[0]['product_title'], $order->sn, $order->real_amount, $notifyUrl)
                        ->setOpenId($user->openid)
                        ->create('JSAPI');
                    return ['code' => 1, 'data' => $options];
                default:
                    return ['code' => -1, 'msg' => '请选择支付方式'];
            }
        } else {
            if ($account == '') {
                return ['code' => -1, 'msg' => '请选择支付方式'];
            }
            return self::operation($order, $user, $account, $param);
        }
    }

    /**
     * @param $order -- 订单信息
     * @param $user -- 会员信息
     * @param $pay_way -- 支付方式
     * @return array
     * 原点 2022年1月8日16:42:02 支付完成后续操作
     */
    public static function operation($order, $user, $pay_way, $param)
    {
        $sys = Config::lists();
        parent::startTrans();
        try {
            //其他后续操作，按需执行

            //更改状态
            $order->pay_state = 2;
            $order->pay_way = $pay_way;
            $order->pay_time = time();
            $order->status = $order->shoptype == 'coupon' ? 5 : 2;
            $order->types = $param['types'];
            if (isset($param['images'])) {
                $order->voucher = $param['images'];
            }
            $order->save();

            //扣钱
            if ($param['types'] == 1) {
                if (in_array($pay_way, ['currency'])) {
                    Target::Account()
                        ->basics($user->id, $pay_way, $order->real_amount, '购买产品', '-')
                        ->createNormal();
                }
            }
            if ($order->shoptype == 'lntegral') {
                Target::Account()
                    ->basics($user->id, 'lntegral', $order->lntegral, '购买积分产品', '-')
                    ->createNormal();
            }
            if ($order->shoptype == 'shop') {
                Target::Account()
                    ->basics($user->id, 'lntegral', round($order->real_amount * $sys['give_bs'], 2), '购买产品赠送积分', '+')
                    ->createNormal();
            }
            if ($order->shoptype == 'coupon') {
                $product_pid = OrderProduct::where('order_id', $order->id)->value('pid');
                $p_id = Lntegral::where('id', $product_pid)->value('coupon_id');
                // print_r($p_id);die;
                Usercoupon::couponAdd(['id' => $p_id], $user);
            }
            /**
             * 增加销售额
             */
            if ($order->shoptype == 'lntegral' || $order->shoptype == 'coupon') {
                $money = $order->money;
            } else {
                $money = $order->real_amount;
            }
            // $user->my_total += $money;
            /**
             * 升级
             */
            $level = Level::where([['money', '<=', $user->my_total], ['money', '>', $user->level_id], ['is_del', '=', 0]])->order('id asc')->find();
            if (!empty($level)) {
                $user->level_id = $level->id;
            }
            $user->save();
            Event::trigger('Operation', $order->id);
            $notify = [
                'uid'     => $user->id,
                'type'    => 1,
                'content' => '下单成功，订单号：' . $order->sn,
                'source'  => $order->id
            ];
            Event::trigger('UserNotify', $notify);
            parent::commit();
            Cache::set('nowOrderId_' . $user->id, null);
            return ['code' => 1, 'msg' => '支付成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 退款申请
     */
    public static function order_refund($param, $user): array
    {
        try {
            $info = parent::where(['id' => $param['order_id'], 'uid' => $user->id, 'is_del' => 0])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '订单不存在'];
            }
            if ($info->getData('status') != 2 && $info->getData('status') != 3) {
                return ['code' => -1, 'msg' => '退款订单状态异常！'];
            }
            $orderrefund = OrderRefund::where(['order_id' => $param['order_id'], 'uid' => $user->id, 'is_del' => 0])->find();

            $param['uid'] = $user->id;
            $param['create_time'] = time();
            if (empty($orderrefund)) {
                OrderRefund::insert($param);
            } else {
                return ['code' => -1, 'msg' => '该订单以申请退款！'];
            }
            $info->refund_status = $info->getData('status');
            $info->status = 7;
            $info->save();
            parent::commit();
            return ['code' => 1, 'msg' => '申请退款成功！请等待平台审核！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $param
     * @param $user
     * @return array
     * 原点 2022年1月8日16:43:09 订单相关操作
     */
    public static function edit($param, $user): array
    {
        try {
            $info = parent::where(['id' => $param['id'], 'uid' => $user->id, 'is_del' => 0])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '订单不存在'];
            }
            switch ($param['type']) {
                case 'clear': //取消订单
                    if ($info->getData('status') != 1 || $info->pay_state) {
                        return ['code' => -1, 'msg' => '订单已支付，无法取消'];
                    }
                    $info->is_del = 1;
                    $info->status = 6;
                    $info->cancel_time = time();
                    $info->save();
                    return ['code' => 1, 'msg' => '订单已取消'];
                case 'payment': //支付订单
                    if ($info->getData('status') != 1) {
                        return ['code' => -1, 'msg' => '订单已支付'];
                    }
                    Cache::set('nowOrderId_' . $user->id, $info->id);
                    return ['code' => 1, 'msg' => '已生成订单', 'types' => $info->types];

                case "remind": //提醒发货
                    if ($info->getData('status') != 2) {
                        return ['code' => -1, 'msg' => '订单未支付或已发货'];
                    }
                    if ($info->is_remind) {
                        return ['code' => -1, 'msg' => '您已提醒发货了！'];
                    }
                    $info->is_remind = 1;
                    $info->remind_time = time();
                    $info->save();
                    return ['code' => 1, 'msg' => '已提醒发货'];

                case "refund": //提醒发货
                    if ($info->getData('status') != 2 || $info->getData('status') != 3) {
                        return ['code' => -1, 'msg' => '该订单不可退款'];
                    }
                    $info->is_remind = 1;
                    $info->remind_time = time();
                    $info->save();
                    return ['code' => 1, 'msg' => '已提醒发货'];
                case "receipt": //确认收货
                    if ($info->getData('status') != 3) {
                        return ['code' => -1, 'msg' => '订单异常'];
                    }
                    $info->status = $info->shoptype == 'lntegral' ? 5 : 4;
                    if ($info->shoptype == 'lntegral') {
                        $info->finish_time = time();
                    }
                    if ($info->shoptype == 'lntegral' || $info->shoptype == 'coupon') {
                        $money = $info->money;
                    } else {
                        $money = $info->real_amount;
                    }
                    $user->my_total += $money;
                    $info->receipt_time = time();
                    $info->save();
                    if ($info['commission_uid1'] != 0 && $info['commission1'] != 0) {
                        Target::Account()
                            ->basics($info['commission_uid1'], 'bonus', $info['commission1'], '一级佣金结算', '+')
                            ->lock(false) //写入流水是否上锁，默认false，开启后会大幅降低性能，开启后必须配合事务使用
                            ->createNormal($info->uid);
                    }
                    if ($info['commission_uid2'] != 0 && $info['commission2'] != 0) {
                        Target::Account()
                            ->basics($info['commission_uid2'], 'bonus', $info['commission2'], '二级佣金结算', '+')
                            ->lock(false) //写入流水是否上锁，默认false，开启后会大幅降低性能，开启后必须配合事务使用
                            ->createNormal($info->uid);
                    }
                    return ['code' => 1, 'msg' => '已确认收货'];
                default:
                    return ['code' => -1, 'msg' => '加载失败'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**------------积分商城----------- */
    /**
     * 获取积分商品订单
     */
    public static function getLntegralTemporary($uid): array
    {
        try {
            $syytem = Config::lists();
            $temporary = Cache::get('tsOrder_' . $uid);
            // print('<pre>');print_r($temporary);die;
            if (empty($temporary)) {
                return ['code' => -1, 'msg' => '加载失败'];
            }
            $infos = json_decode($temporary, true);
            $total = 0;
            $num = 0;
            $cate_1 = '';
            $products = [];
            foreach ($infos as $value) {
                $product = Lntegral::where(['is_del' => 0, 'status' => 1, 'id' => $value['pid']])
                    ->field('id,title,icon,stock')->find();
                if (empty($product) || $product->stock <= 0) continue;
                $total += $value['price'] * $value['num'];
                $num += $value['num'];
                $product->num = $value['num'];
                $product->price = $value['price'];
                $shoptype = $value['shoptype'];
                $product->spec = $value['spec'];
                if (!$cate_1) $cate_1 = $value['cate_1'];
                $ids[] = $value['pid'];
                $products[] = $product;
            }
            return [
                'products'    => $products,
                'total'       => sprintf('%.2f', $total),
                'cate_1'      => $cate_1,
                'num'         => $num,
                'infos'   => count($infos),
                'shoptype'    => $shoptype,
                'address'     => Address::getDefault($uid, $total, $products, $num)
            ];
        } catch (\Exception $e) {
            return [];
        }
    }
    /**
     * 获取订单缓存信息
     */
    public static function getOrderLntegralTemporary($uid): array
    {
        try {
            $temporary = Cache::get('tsOrder_' . $uid);
            if (empty($temporary)) {
                return ['code' => -1, 'msg' => '加载失败'];
            }
            $infos = json_decode($temporary, true);
            $total = 0;
            $num = 0;
            $cate_1 = '';
            $products = [];
            foreach ($infos as $value) {
                $product = Lntegral::where(['is_del' => 0, 'status' => 1, 'id' => $value['pid']])
                    ->field('id,title,icon,stock')->find();
                if (empty($product) || $product->stock <= 0) continue;
                $total += $value['price'] * $value['num'];
                $num += $value['num'];
                $product->num = $value['num'];
                $product->price = $value['price'];
                $product->seckill_id = 0;
                $shoptype = $value['shoptype'];
                $product->shoptype = $value['shoptype'];
                $product->spec = $value['spec'];
                if (!$cate_1) $cate_1 = $value['cate_1'];
                $products[] = $product;
            }
            return [
                'products'    => $products,
                'total'       => sprintf('%.2f', $total),
                'cate_1'      => $cate_1,
                'num'         => $num,
                'shoptype'    => $shoptype,
            ];
        } catch (\Exception $e) {
            return [];
        }
    }
    /**
     * 提交积分订单
     */
    public static function orderSubmit($param, $user): array
    {
        if (!$param['address_id']) {
            return ['code' => -1, 'msg' => '请选择收货地址'];
        }
        $address = Address::where('id', $param['address_id'])->find();
        if (empty($address)) {
            return ['code' => -1, 'msg' => '收货地址错误，请重新选择'];
        }
        $temporary = self::getOrderLntegralTemporary($user->id);

        if (empty($temporary) || empty($temporary['products'])) {
            return ['code' => -1, 'msg' => '加载失败，请稍后再试'];
        }
        if (!$temporary['total'] || $temporary['total'] <= 0) {
            return ['code' => -1, 'msg' => '订单价格错误！'];
        }

        parent::startTrans();
        try {
            $new = parent::create([
                'sn'              => date('Ymd') . $user->id . time(),
                'uid'             => $user->id,
                'address_id'      => $param['address_id'],
                'total_amount'    => $param['total_amount'],
                'real_amount'     => $param['real_amount'],
                'make'            => $param['make'],
                'make_type'       => $param['make_type'],
                'make_status'     => $param['make_status'],
                'note'            => $param['note'],
                'types'           => 1,
                'postage'         => 0,
                'order_type'      => $temporary['cate_1'],
                'shoptype'        => $temporary['shoptype'],
                'receiver'        => $address->nickname,
                'receiver_tel'    => $address->tel,
                'province'        => $address->province,
                'city'            => $address->city,
                'district'        => $address->district,
                'address_details' => $address->details,
            ]);
            $flag = OrderProduct::add($temporary['products'], $new->id, $user->id);
            if ($flag['code'] != 1) {
                parent::rollback();
                return ['code' => -1, 'msg' => $flag['msg']];
            }
            parent::commit();
            Cart::clearCart($user->id);
            Cache::set('nowOrderId_' . $user->id, $new->id);
            return ['code' => 1, 'msg' => '已生成订单'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取收银台
     */
    public static function getNowLntegralOrder($user): array
    {
        $buy_bs = Config::lists()['buy_bs'];
        $uid = $user->id;
        $now_id = Cache::get('nowOrderId_' . $uid);
        if (!$now_id) {
            return ['code' => -1, 'msg' => '加载失败'];
        }
        $info = parent::where(['id' => $now_id, 'uid' => $uid, 'status' => 1, 'pay_state' => 0])->find();
        if (empty($info)) {
            return ['code' => -1, 'msg' => '订单不存在或已支付'];
        }
        $user_lntegral = $user->assets->lntegral;
        $real_amount = $info['real_amount'];
        if (($user_lntegral - $real_amount) >= 0) {
            $lntegral = $real_amount;
            $money = 0;
        } else {
            $lntegral = $user_lntegral;
            $money = round(($real_amount - $user_lntegral) / $buy_bs, 2);
        }
        $info->lntegral = $lntegral;
        $info->money = $money;
        $info->save();
        return ['code' => 1, 'result' => $info];
    }
    /**
     * 确认支付
     */
    public static function confirmlLntegralPayment($param, $user): array
    {
        $info = self::getNowLntegralOrder($user);
        if ($info['code'] != 1) return $info;
        $order = $info['result'];

        $account = $param['pay_way'];
        $param['types'] = 1;
        switch ($account) {
            case "lntegral":
                if ($user->assets->$account < $order->lntegral) {
                    return ['code' => -1, 'msg' => '账户余额不足'];
                }
                return self::operation($order, $user, $account, $param);
            case "group_pay":
                if ($user->assets->lntegral < $order->lntegral) {
                    return ['code' => -1, 'msg' => '积分余额不足'];
                }
                $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/api/callback/weChatOrder';
                $options = Pay::setDriver('WeChat')
                    ->basic('购买积分商品', $order->sn, $order->money, $notifyUrl)
                    ->setOpenId($user->openid)
                    ->create('JSAPI');
                return ['code' => 1, 'data' => $options];
            default:
                return ['code' => -1, 'msg' => '请选择支付方式'];
        }
    }
}
